<?php

namespace haibao\erp\business\brand;

use haibao\erp\data\brand\BrandDefine as BrandDefineData;
use haibao\erp\model\filter\brand\BrandDefine as BrandDefineFilter;
use haibao\erp\business\BusinessException;
use haibao\frame\data\query\Condition;

class BrandDefine extends \haibao\erp\business\Base{
	
	/**
	 * 获取所有品牌
	 */
	public static function getAll($query){
		$brandDefineData = new BrandDefineData();
		return $brandDefineData->getAll($query);
	}
	/**
	 * 获取单个品牌
	 */
	public static function getOne($query){
		$brandDefineData = new BrandDefineData();
		return $brandDefineData->getOne($query);
	}
	
	/**
	 * 保存品牌
	 */
	public static function saveBrand($brandModel){
		$funCode = $brandModel->Id ? self::FUNC_CODE_BRAND_EDIT : self::FUNC_CODE_BRAND_ADD;
		self::checkOperation($funCode);
		if(!$brandModel->BrandCH){
			throw new BusinessException('中文名不能为空',self::DATA_EMPTY_NAME);
		}
		if(!$brandModel->BrandEN){
			throw new BusinessException('英文名不能为空',self::DATA_EMPTY_NAME);
		}
		if(!$brandModel->Id){
			$brandModel->CreateTime = new \DateTime();
			$brandModel->CreateBy =  self::getCurrentUser()->Id;
		}
		$brandData = new BrandDefineData();
		return $brandData->saveBrand($brandModel);
		self::saveOperateHistory($funCode, $brandModel->toArray());
		
	}
	/**
	 * 根据id删除品牌
	 */
	public static function delBrandById($brandId){
		self::checkOperation(self::FUNC_CODE_BRAND_DELETE);
		if(!$brandId){
			throw new BusinessException('品牌Id不能为空');
		}
		$data = new BrandDefineData();
		$data->delBrandById($brandId);
		self::saveOperateHistory(self::FUNC_CODE_BRAND_DELETE, $brandId);
	}
	/**
	 * 判断重名
	 */
	public static function checkUniqueBrandName($nameCH,$nameEN,$brandId = 0){
		$brandInfo = array();
		$brandFilter = new BrandDefineFilter();
		$brandFilter->select(array(
				$brandFilter::CONDITION_FIELD_NAME_ID,
				$brandFilter::CONDITION_FIELD_NAME_BRANDCH
		));
		$brandFilter->where($brandFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_OR, array(
				new Condition($brandFilter::CONDITION_FIELD_NAME_BRANDCH,Condition::CONDITION_EQUAL,$nameCH),
				new Condition($brandFilter::CONDITION_FIELD_NAME_BRANDEN,Condition::CONDITION_EQUAL,$nameEN)
		));
		if($brandId){
			$brandFilter->where($brandFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_NOTEQUAL, (int)$brandId);
		}
		
		$brandInfo = self::getOne($brandFilter);
		
		if($brandInfo){
			throw new BusinessException('品牌名已存在',self::DATA_ERROR_NAME_EXIST);
		}
		
	}
	
}